package com.wsy.shiro.controller;

import com.wsy.shiro.vo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangshangyi
 * @version V1.0  2020/8/31 11:42
 */
@RestController
public class UserController {
    @PostMapping(value="/doLogin",produces = "application/json;charset=UTF-8")
    public String login(User user){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "用户名或密码不正确";
        }

        try {
            subject.checkRole("admin");
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return "no Role";
        }

        try {
            subject.checkPermission("user:add");
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return "no Permission";
        }
        return "登录成功";
    }

    //只有拥有admin权限的用户才能进入这个接口,参数可以是多个
    @RequiresRoles("admin")
    @GetMapping("/testRole")
    private String testRole(){
        return "success";
    }

    @RequiresRoles("admin2")
    @GetMapping("/testRole1")
    private String testRole1(){
        return "success";
    }

    //logical 默认值是and 表示多个权限，必须都满足 logical = Logical.AND
    @RequiresPermissions(value={"user:add,userSelect"},logical = Logical.OR)
    @GetMapping("/testPermission")
    private String testPermission(){
        return "success";
    }

    @GetMapping("/testRole2")
    private String testRole2(){
        return "testRole2 success";
    }
    @GetMapping("/testRole3")
    private String testRole3(){
        return "testRole3 success";
    }
    @GetMapping("/testPermission2")
    private String testPermission2(){
        return "testPermission2 success";
    }
    @GetMapping("/testPermission3")
    private String testPermission3(){
        return "testPermission3 success";
    }

}
